using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
using Microsoft.Xna.Framework.Net;
using Microsoft.Xna.Framework.Storage;

namespace VectorTypeSwap
{
    /// <summary>
    /// This is the main type for your game
    /// </summary>
    public class Game1 : Microsoft.Xna.Framework.Game
    {
        private GraphicsDeviceManager graphicsDeviceManager;
        private SpriteBatch spriteBatch;
        private bool isKeyEscapeDown;
        private Model cube;
        private BasicEffect basicEffect;

        public Game1()
        {
            this.graphicsDeviceManager = new GraphicsDeviceManager(this);
            Content.RootDirectory = "Content";

            IsMouseVisible = true;
        }

        /// <summary>
        /// Allows the game to perform any initialization it needs to before starting to run.
        /// This is where it can query for any required services and load any non-graphic
        /// related content.  Calling base.Initialize will enumerate through any components
        /// and initialize them as well.
        /// </summary>
        protected override void Initialize()
        {
            this.basicEffect = new BasicEffect(this.GraphicsDevice, null);
            this.basicEffect.World = Matrix.CreateTranslation(new Vector3(0, -0.5f, 0));
            this.basicEffect.View = Matrix.CreateLookAt(new Vector3(2, 1, 5), Vector3.Zero, Vector3.Up);
            this.basicEffect.Projection = Matrix.CreatePerspectiveFieldOfView(MathHelper.ToRadians(45),
                                                                               (float)this.Window.ClientBounds.Width /
                                                                               (float)this.Window.ClientBounds.Height,
                                                                               0.1f,
                                                                               20f);

            base.Initialize();
        }

        /// <summary>
        /// LoadContent will be called once per game and is the place to load
        /// all of your content.
        /// </summary>
        protected override void LoadContent()
        {
            // Create a new SpriteBatch, which can be used to draw textures.
            spriteBatch = new SpriteBatch(GraphicsDevice);

            cube = Content.Load<Model>( "cube" );
            
            foreach (ModelMesh cubeMesh in cube.Meshes)
            {
                foreach (ModelMeshPart part in cubeMesh.MeshParts)
                {
                    VertexPositionColor[] vertices = new VertexPositionColor[part.NumVertices];
                    short[] indices = new short[cubeMesh.IndexBuffer.SizeInBytes / sizeof(short)];

                    cubeMesh.VertexBuffer.GetData<VertexPositionColor>(part.StreamOffset, vertices, part.StartIndex, part.NumVertices, part.VertexStride);
                    cubeMesh.IndexBuffer.GetData<short>( indices );

                    for ( int i = 0; i < vertices.Length; i++ )
                    {
                        vertices[i].Color = Color.Yellow;
                    }

                    VertexBuffer vertexBuffer = new VertexBuffer( GraphicsDevice,
                                                                  VertexPositionColor.SizeInBytes * vertices.Length,
                                                                  BufferUsage.None );
                    IndexBuffer indexBuffer = new IndexBuffer( GraphicsDevice,
                                                               sizeof(short) * indices.Length,
                                                               BufferUsage.None,
                                                               IndexElementSize.SixteenBits );

                    vertexBuffer.SetData<VertexPositionColor>( vertices );
                    indexBuffer.SetData<short>( indices );

                    GraphicsDevice.VertexDeclaration = new VertexDeclaration( GraphicsDevice, VertexPositionColor.VertexElements );
                    GraphicsDevice.Vertices[0].SetSource( vertexBuffer, 0, VertexPositionColor.SizeInBytes );
                    GraphicsDevice.Indices = indexBuffer;
                }
            }
        }

        /// <summary>
        /// Allows the game to run logic such as updating the world,
        /// checking for collisions, gathering input, and playing audio.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Update(GameTime gameTime)
        {
            // Allows the game to exit
            if (Keyboard.GetState().IsKeyUp(Keys.Escape) &&
                 this.isKeyEscapeDown)
            {
                this.Exit();
            }

            isKeyEscapeDown = Keyboard.GetState().IsKeyDown( Keys.Escape );

            base.Update(gameTime);
        }

        /// <summary>
        /// This is called when the game should draw itself.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Draw(GameTime gameTime)
        {
            GraphicsDevice.Clear(Color.CornflowerBlue);

            //GraphicsDevice.RenderState.FillMode = FillMode.WireFrame;
            GraphicsDevice.RenderState.CullMode = CullMode.None;

            basicEffect.World *= Matrix.CreateRotationY( MathHelper.ToRadians( 1 ) );

            foreach (ModelMesh cubeMesh in cube.Meshes)
            {
                foreach ( BasicEffect cubeEffect in cubeMesh.Effects )
                {
                    cubeEffect.World = this.basicEffect.World;
                    cubeEffect.View = this.basicEffect.View;
                    cubeEffect.Projection = this.basicEffect.Projection;

                    cubeEffect.EnableDefaultLighting();
                    cubeEffect.VertexColorEnabled = true; // <-- Doesn't do anything!
                }

                // Draw the cube model
                //cubeMesh.Draw();
            }

            // Draw the vertices
            basicEffect.Begin();

            basicEffect.VertexColorEnabled = true;

            foreach (EffectPass pass in basicEffect.CurrentTechnique.Passes)
            {
                pass.Begin();
                GraphicsDevice.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0, 0, 8, 0, 12);
                pass.End();
            }

            basicEffect.End();

            base.Draw(gameTime);
        }
    }
}